# db.py
# 数据库相关操作
import psycopg2
from config import DB_HOST, DB_PORT, DB_NAME, DB_USER, DB_PASSWORD

def get_conn():
    """
    获取数据库连接
    """
    conn = psycopg2.connect(
        host=DB_HOST,
        port=DB_PORT,
        dbname=DB_NAME,
        user=DB_USER,
        password=DB_PASSWORD
    )
    return conn

def insert_lsbmzd(data_list):
    """
    批量插入数据到lsbmzd表
    :param data_list: List[dict]，每个dict为一条数据
    """
    conn = get_conn()
    cur = conn.cursor()
    sql = """
    INSERT INTO lsbmzd (dwbh, bmbh, bmmc, js, mx)
    VALUES (%s, %s, %s, %s, %s)
    """
    for item in data_list:
        # 取出每个字段，注意字段名要和接口返回一致
        cur.execute(sql, (
            item["LSBMZD_DWBH"],
            item["LSBMZD_BMBH"],
            item["LSBMZD_BMMC"],
            item["LSBMZD_JS"],
            item["LSBMZD_MX"]
        ))
    conn.commit()
    cur.close()
    conn.close() 